// user.controller.ts
// import { omit } from 'lodash'
import { ALL, Body, Controller, Del, Get, Inject, Post, Provide, Put, Query } from '@midwayjs/core';
import { UserService } from '../service/user';
import { BindStoreDTO, LoginUserDTO, UpdateUserDTO, UploadPwdDTO, UserDTO } from '../dto/user';
import { Validate } from '@midwayjs/validate';
import User from '../entity/user';
import { BaseError } from '../../../common/base.error';
import { NotLogin } from '../../../decorator/not.login';
import { setObjAttrToCls } from '../../../utils';
const dayjs = require('dayjs');


@Provide()
@Controller('/user')
export class UserController {
  
  @Inject()
  userService: UserService;

  @Post('/')
  @NotLogin()
  @Validate()
  async create(@Body(ALL) data: UserDTO) {
    const user = new User();
    return this.userService.createUser(setObjAttrToCls(user, User, data));
  }

  @Put('/')
  @Validate()
  async edit(@Body(ALL) data: UpdateUserDTO) {
    const user = await this.userService.getById(data.id);
    return await this.userService.edit(setObjAttrToCls(user, User, data))
  }

  @Del('/:id')
  async remove(@Body(ALL) data: UserDTO) {
    const user = await this.userService.getById(data.id);
    return await this.userService.remove(user)
  }

  @Get('/page')
  async page(@Query('page') page: number, @Query("size") size: number) {
    if (!page) {
      throw BaseError.validateError("page不能为空！");
    }

    if (!size) {
      throw BaseError.validateError("size不能为空！");
    }

    return await this.userService.pages(page, size)
  }

  @Get('/list')
  async list() {
    return await this.userService.getList({ relations: ['store'] })
  }

  @Post('/login')
  async login(@Body() data: LoginUserDTO) {
    const user = new User();
    user.username = data.username;
    user.password = data.password;
    return await this.userService.login(user)
  }

  @Get('/info')
  async getUserInfo() {
    return await this.userService.getUserInfo();
  }

  @Put('/info')
  async updateUserInfo(@Body() data: UpdateUserDTO) {
    const { nickname, phone, avatar, role } = data;
    const user = await this.userService.getById(data.id);
    user.nickname = nickname;
    user.phone = phone;
    user.avatar = avatar;
    user.role = role;
    user.update_date = dayjs().format('YYYY-MM-DD HH:mm:ss');
    return await this.userService.edit(user);
  }

  @Put('/pwd')
  async updatePassword(@Body() data: UploadPwdDTO) {
    const { password, newPassword } = data;
    return this.userService.updatePwd(password, newPassword)
  }

  @Put('/bindStore')
  async bindStore(@Body(ALL) data: BindStoreDTO) {
    return this.userService.bindStore(data)
  }
}